package com.basic.backend.service.impl;

import com.basic.backend.common.ErrorCode;
import com.basic.backend.config.RabbitMQConfig;
import com.basic.backend.exception.BusinessException;
import com.basic.backend.model.dto.Images.ImageAnalysisDTO;
import com.basic.backend.model.dto.analysis.ArticleAnalysisDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
@Slf4j
public class MessageProducer {

    @Resource
    private RabbitTemplate rabbitTemplate;

    public void sendAnalysisTask(ArticleAnalysisDTO dto) {
        try {
            rabbitTemplate.convertAndSend(
                    RabbitMQConfig.ARTICLE_QUEUE,
                    dto,
                    message -> {
                        message.getMessageProperties().setContentType("application/json");
                        return message;
                    });
            log.info("文章分析任务已发送：{}", dto.getArticleId());
        } catch (Exception e) {
            log.error("消息发送失败，articleId: {}", dto.getArticleId(), e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "分析任务提交失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void sendImageAnalysisTask(ImageAnalysisDTO dto) {
        rabbitTemplate.convertAndSend(
                RabbitMQConfig.IMAGE_QUEUE,
                dto,
                message -> {
                    message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                    message.getMessageProperties().setHeader("X-Producer-Time", System.currentTimeMillis());
                    return message;
                }
        );
        log.info("事务消息已暂存 articleId={}", dto.getArticleId());
    }
}